// 按序列执行函数

type IEventInfo = { event: Function; name?: string }
export const uesEventSequence = (config?: { distinct?: boolean }) => {
  const { distinct = false } = config || {}
  const starting = ref<string | boolean>(false) // 是否在执行中|执行中的事件的name
  const eventsList = ref<IEventInfo[]>([])

  function append(event: Function, name?: string) {
    if (distinct && (eventsList.value.map((e) => e.name).includes(name) || starting.value === name))
      return console.log('uesEventSequence:事件已存在，不加入队列')
    eventsList.value.push({ event, name })
  }

  watch(
    () => eventsList.value.length,
    (len) => {
      if (len && !starting.value) {
        ;(async function start() {
          const { event, name } = eventsList.value.shift() as IEventInfo
          starting.value = name || true
          await event()
          if (eventsList.value.length)
            start() // continue
          else starting.value = false // stop
        })()
      }
    },
  )

  return { append, starting }
}
